package com.ezjie.ielts.view;

import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import com.ezjie.ielts.R;
import com.ezjie.ielts.util.DensityUtil;

public class CircleProgressView extends View {

	private final Paint paint;
	private final Context context;

	private float rate;
	private float total;

	public void setProgressValues(float rate, float total) {
		this.rate = rate;
		this.total = total;
	}

	public CircleProgressView(Context context) {
		this(context, null);
	}

	public CircleProgressView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		this.paint = new Paint();
		this.paint.setAntiAlias(true); // 消除锯齿
		this.paint.setStyle(Paint.Style.STROKE); // 绘制空心圆
		this.paint.setStrokeWidth(DensityUtil.dip2px(context, 2)); // 画笔宽度
	}

	@Override
	protected void onDraw(Canvas canvas) {
		float center = getWidth() / 2;
		float circleRadius = center - DensityUtil.dip2px(context, 2); // 设置圆半径

		// 绘制底层圆
		this.paint.setColor(Color.parseColor("#ffe5e5e5"));
		canvas.drawCircle(center, center, circleRadius, this.paint);

		// 绘制进度弧形
		this.paint.setColor(Color.parseColor("#ffffb200"));
		RectF oval = new RectF(center - circleRadius, center - circleRadius, center + circleRadius, center
				+ circleRadius);
		float sweepAngle = rate / total;
		canvas.drawArc(oval, -90, 360 * sweepAngle, false, paint);

		// 绘制进度文本
		float textSize = 16;
		Paint textPaint = new Paint();
		textPaint.setColor(Color.parseColor("#ffffb200"));
		textPaint.setAntiAlias(true);
		try {
			textSize = context.getResources().getDimension(R.dimen.normal_size);
			textPaint.setTextSize(textSize);
		} catch (NotFoundException e) {
			e.printStackTrace();
			textPaint.setTextSize(textSize);
		}

		String ratestr = rate <= 0 ? context.getResources().getString(R.string.read_classify_no_rate) : String.format(
				"%.0f", rate);

		float textWidth = textPaint.measureText(ratestr); // 测量字体宽度，我们需要根据字体的宽度设置在圆环中间

		canvas.drawText(ratestr, center - textWidth / 2, center + textSize / 2 - 2, textPaint); // 画出进度百分比

		super.onDraw(canvas);
	}

}
